// pages/withdrawPoints/withdrawPoints.js
Page({
    data: {
        statusBarHeight: 0,
        points: 0, // 可用积分
        withdrawAmount: '', // 提现金额
        bankCards: [], // 银行卡列表
        selectedCardId: '', // 选中的银行卡ID
        selectedBankName: '', // 选中的银行名称
        selectedCardNumber: '', // 选中的银行卡号（后四位）
        maxWithdraw: 0, // 最大可提现积分
        isFormValid: false // 表单是否有效
    },

    onLoad() {
        // 获取状态栏高度
        const systemInfo = wx.getSystemInfoSync();
        this.setData({
            statusBarHeight: systemInfo.statusBarHeight
        });

        // 加载用户积分和银行卡信息
        this.getUserPoints();
        this.getBankCards();
    },

    onShow() {
        // 每次显示页面时刷新银行卡信息
        this.getBankCards();
    },

    // 获取用户积分
    getUserPoints() {
        wx.cloud.callFunction({
            name: 'getUserPoints',
            data: {
                userId: wx.getStorageSync('userInfo')._id
            },
            success: (res) => {
                console.log(res);
                if (res.result.success) {
                    this.setData({
                        points: res.result.points || 0,
                        maxWithdraw: Math.floor(res.result.points / 10) * 10 // 只能提现100的整数倍
                    });
                    console.log(this.data.maxWithdraw);
                    this.validateForm();
                }
            },
            fail: (err) => {
                console.error('获取积分失败:', err);
            }
        });
    },

    // 获取银行卡列表
    getBankCards() {
        wx.cloud.callFunction({
            name: 'getUserBankCards',
            data: {
                userId: wx.getStorageSync('userInfo')._id
            },
            success: (res) => {
                console.log(res);
                if (res.result.success) {
                    const cards = res.result.cards || [];
                    let selectedCardId = this.data.selectedCardId;
                    let selectedBankName = '';
                    let selectedCardNumber = '';

                    // 如果没有选中的卡，尝试选择默认卡
                    if (!selectedCardId && cards.length > 0) {
                        const defaultCard = cards.find(card => card.isDefault);
                        if (defaultCard) {
                            selectedCardId = defaultCard._id;
                            selectedBankName = defaultCard.bankName;
                            selectedCardNumber = defaultCard.cardNumberDisplay;
                        } else if (cards.length > 0) {
                            selectedCardId = cards[0]._id;
                            selectedBankName = cards[0].bankName;
                            selectedCardNumber = cards[0].cardNumberDisplay;
                        }
                    } else {
                        // 查找选中的卡信息
                        const selectedCard = cards.find(card => card._id === selectedCardId);
                        if (selectedCard) {
                            selectedBankName = selectedCard.bankName;
                            selectedCardNumber = selectedCard.cardNumberDisplay;
                        }
                    }

                    this.setData({
                        bankCards: cards,
                        selectedCardId: selectedCardId,
                        selectedBankName: selectedBankName,
                        selectedCardNumber: selectedCardNumber
                    });
                    this.validateForm();
                }
            },
            fail: (err) => {
                console.error('获取银行卡列表失败:', err);
            }
        });
    },

    // 选择银行卡
    selectBankCard() {
        if (this.data.bankCards.length === 0) {
            // 如果没有银行卡，跳转到添加银行卡页面
            wx.showModal({
                title: '提示',
                content: '您还没有绑定银行卡，是否前往绑定？',
                success: (res) => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/bindBankCard/bindBankCard'
                        });
                    }
                }
            });
            return;
        }

        // 跳转到银行卡列表页
        wx.navigateTo({
            url: '/pages/bankCards/bankCards'
        });
    },

    // 输入提现金额
    onAmountInput(e) {
        console.log(e);
        console.log(this.data.maxWithdraw);
        let amount = e.detail.value;

        // 限制只能输入数字
        amount = amount.replace(/[^\d]/g, '');

        // 如果用户删除所有内容，允许空值
        if (amount === '') {
            this.setData({
                withdrawAmount: ''
            });
            this.validateForm();
            return;
        }

        // 转换为数字并检查有效性
        const numericAmount = parseInt(amount);

        // 限制最大输入值
        if (numericAmount > this.data.maxWithdraw) {
            amount = this.data.maxWithdraw.toString();
        }

        // // 限制为100的整数倍
        // if (numericAmount % 100 !== 0) {
        //     // 自动调整为最近的100的整数倍（向下取整）
        //     const validAmount = Math.floor(numericAmount / 100) * 100;
        //     amount = validAmount.toString();
        // }

        // // 自动补全末尾的00（如果用户只输入了百位以上的数字）
        // if (amount.length >= 3 && !amount.endsWith('00')) {
        //     amount = `${amount}00`;
        // }

        this.setData({
            withdrawAmount: amount
        });
        this.validateForm();
    },

    // 全部提现
    withdrawAll() {
        if (this.data.maxWithdraw > 0) {
            this.setData({
                withdrawAmount: this.data.maxWithdraw.toString()
            });
            this.validateForm();
        }
    },

    // 验证表单
    validateForm() {
        const {
            points,
            withdrawAmount,
            selectedCardId
        } = this.data;

        // 检查提现金额是否有效
        const validAmount = withdrawAmount &&
            parseInt(withdrawAmount) >= 10 &&
            parseInt(withdrawAmount) <= points &&
            parseInt(withdrawAmount) % 10 === 0;

        // 检查是否选择了银行卡
        const hasSelectedCard = selectedCardId !== '';

        // 更新表单有效性
        this.setData({
            isFormValid: validAmount && hasSelectedCard
        });
    },

    // 提交提现申请
    submitWithdraw() {
        const {
            withdrawAmount,
            points,
            selectedCardId,
            bankCards
        } = this.data;

        if (!this.data.isFormValid) {
            wx.showToast({
                title: '请填写有效信息',
                icon: 'none'
            });
            return;
        }

        const amount = parseInt(withdrawAmount);

        // 查找选中的银行卡
        const selectedCard = bankCards.find(card => card._id === selectedCardId);

        if (!selectedCard) {
            wx.showToast({
                title: '请选择银行卡',
                icon: 'none'
            });
            return;
        }

        wx.showModal({
            title: '确认提现',
            content: `您确定要提现 ${amount} 积分到${selectedCard.bankName}(${selectedCard.cardNumberDisplay}) 吗？`,
            success: (res) => {
                if (res.confirm) {
                    wx.showLoading({
                        title: '加载中...',
                    });
                    // 调用云函数提交提现申请
                    wx.cloud.callFunction({
                        name: 'withdrawPoints',
                        data: {
                            userId: wx.getStorageSync('userInfo')._id,
                            userName: wx.getStorageSync('userInfo').nickName,
                            amount: amount,
                            cardId: selectedCardId
                        },
                        success: (res) => {
                            wx.hideLoading();
                            console.log(res);
                            if (res.result.success) {
                                wx.showToast({
                                    title: '提现申请已提交',
                                    icon: 'none'
                                });

                                // 返回上一页
                                setTimeout(() => {
                                    wx.navigateBack();
                                }, 1500);
                            } else {
                                wx.showToast({
                                    title: res.result.message || '提现失败',
                                    icon: 'none'
                                });
                            }
                        },
                        fail: (err) => {
                            wx.hideLoading();
                            console.error('提现失败:', err);
                            wx.showToast({
                                title: '提现失败，请重试',
                                icon: 'none'
                            });
                        }
                    });
                }
            }
        });
    },

    // 返回上一页
    goBack() {
        wx.navigateBack();
    }
});